using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using VotingSystem.Models;
using VotingSystem.ViewModels;
using Microsoft.EntityFrameworkCore;
using VotingSystem.Data;
using System.Text.RegularExpressions;

namespace VotingSystem.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly ILogger<AccountController> _logger;
        private readonly ApplicationDbContext _context;

        // 用户名正则表达式：3-20位字母、数字、下划线
        private static readonly Regex UsernameRegex = new(@"^[a-zA-Z0-9_]{3,20}$");
        
        // 密码正则表达式：6-20位字母、数字、下划线
        private static readonly Regex PasswordRegex = new(@"^[a-zA-Z0-9_]{6,20}$");
        
        // 邮箱正则表达式
        private static readonly Regex EmailRegex = new(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$");

        public AccountController(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            ILogger<AccountController> logger,
            ApplicationDbContext context)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _context = context;
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // 验证用户名格式
                    if (!UsernameRegex.IsMatch(model.UserName))
                    {
                        ModelState.AddModelError("UserName", "用户名必须是3-20位字母、数字或下划线");
                        return View(model);
                    }

                    // 验证密码格式
                    if (!PasswordRegex.IsMatch(model.Password))
                    {
                        ModelState.AddModelError("Password", "密码必须是6-20位字母、数字或下划线");
                        return View(model);
                    }

                    // 验证邮箱格式
                    if (!EmailRegex.IsMatch(model.Email))
                    {
                        ModelState.AddModelError("Email", "请输入有效的邮箱地址");
                        return View(model);
                    }

                    // 检查用户名是否已存在
                    var existingUser = await _userManager.FindByNameAsync(model.UserName);
                    if (existingUser != null)
                    {
                        ModelState.AddModelError("UserName", "该用户名已被使用");
                        return View(model);
                    }

                    // 检查邮箱是否已存在
                    var existingEmail = await _userManager.FindByEmailAsync(model.Email);
                    if (existingEmail != null)
                    {
                        ModelState.AddModelError("Email", "该邮箱已被使用");
                        return View(model);
                    }

                    // 检查密码强度
                    if (model.Password.Length < 6)
                    {
                        ModelState.AddModelError("Password", "密码长度不能少于6个字符");
                        return View(model);
                    }

                    // 检查密码是否包含用户名
                    if (model.Password.Contains(model.UserName))
                    {
                        ModelState.AddModelError("Password", "密码不能包含用户名");
                        return View(model);
                    }

                    // 检查密码是否过于简单
                    if (IsSimplePassword(model.Password))
                    {
                        ModelState.AddModelError("Password", "密码过于简单，请使用更复杂的密码");
                        return View(model);
                    }

                    var user = new ApplicationUser
                    {
                        UserName = model.UserName,
                        Email = model.Email,
                        RegisterTime = DateTime.Now,
                        PlainPassword = model.Password
                    };

                    // 创建用户
                    var result = await _userManager.CreateAsync(user);
                    if (result.Succeeded)
                    {
                        _logger.LogInformation("用户 {UserName} 注册成功", model.UserName);
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }

                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "注册过程中发生错误");
                    ModelState.AddModelError(string.Empty, "注册过程中发生错误，请稍后重试");
                }
            }
            return View(model);
        }

        // 检查密码是否过于简单
        private bool IsSimplePassword(string password)
        {
            // 检查是否全是数字
            if (password.All(char.IsDigit))
                return true;

            // 检查是否全是字母
            if (password.All(char.IsLetter))
                return true;

            // 检查是否全是小写字母
            if (password.All(char.IsLower))
                return true;

            // 检查是否全是相同字符
            if (password.Distinct().Count() == 1)
                return true;

            // 检查是否是连续的数字或字母
            if (IsSequential(password))
                return true;

            return false;
        }

        // 检查是否是连续的数字或字母
        private bool IsSequential(string input)
        {
            // 检查数字序列
            if (input.All(char.IsDigit))
            {
                for (int i = 0; i < input.Length - 1; i++)
                {
                    if (input[i + 1] - input[i] != 1)
                        return false;
                }
                return true;
            }

            // 检查字母序列
            if (input.All(char.IsLetter))
            {
                for (int i = 0; i < input.Length - 1; i++)
                {
                    if (input[i + 1] - input[i] != 1)
                        return false;
                }
                return true;
            }

            return false;
        }

        [HttpGet]
        public IActionResult Login(string? returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model, string? returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                try
                {
                    // 验证用户名格式
                    if (!UsernameRegex.IsMatch(model.UserName))
                    {
                        ModelState.AddModelError("UserName", "用户名格式不正确");
                        return View(model);
                    }

                    // 验证密码格式
                    if (!PasswordRegex.IsMatch(model.Password))
                    {
                        ModelState.AddModelError("Password", "密码格式不正确");
                        return View(model);
                    }

                    // 查找用户
                    var user = await _userManager.FindByNameAsync(model.UserName);
                    if (user == null)
                    {
                        ModelState.AddModelError(string.Empty, "用户名或密码错误");
                        return View(model);
                    }

                    // 直接比较密码
                    if (user.PlainPassword != model.Password)
                    {
                        ModelState.AddModelError(string.Empty, "用户名或密码错误");
                        return View(model);
                    }

                    // 登录成功
                    await _signInManager.SignInAsync(user, model.RememberMe);
                    _logger.LogInformation("用户 {UserName} 登录成功", model.UserName);
                    return RedirectToLocal(returnUrl);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "登录过程中发生错误");
                    ModelState.AddModelError(string.Empty, "登录过程中发生错误，请稍后重试");
                }
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            _logger.LogInformation("用户已登出");
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public async Task<IActionResult> Profile()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            var voteRecords = await _context.VoteRecords
                .Include(r => r.Vote)
                .Include(r => r.Option)
                .Where(r => r.UserId == user.Id)
                .OrderByDescending(r => r.VoteTime)
                .ToListAsync();

            var model = new UserProfileViewModel
            {
                Id = user.Id,
                UserName = user.UserName!,
                Email = user.Email!,
                RegisterTime = user.RegisterTime,
                CreatedVotesCount = await _context.Votes.CountAsync(v => v.CreatorId == user.Id),
                ParticipatedVotesCount = await _context.VoteRecords.CountAsync(r => r.UserId == user.Id)
            };

            return View(model);
        }

        [HttpGet]
        public IActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
            if (result.Succeeded)
            {
                await _signInManager.RefreshSignInAsync(user);
                _logger.LogInformation("用户 {UserName} 修改密码成功", user.UserName);
                return RedirectToAction(nameof(Profile));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> EditProfile()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            var model = new EditProfileViewModel
            {
                UserName = user.UserName!,
                Email = user.Email!
            };

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> EditProfile(EditProfileViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            // 检查用户名是否已被使用
            if (user.UserName != model.UserName)
            {
                var existingUser = await _userManager.FindByNameAsync(model.UserName);
                if (existingUser != null)
                {
                    ModelState.AddModelError("UserName", "该用户名已被使用");
                    return View(model);
                }
                user.UserName = model.UserName;
            }

            // 检查邮箱是否已被使用
            if (user.Email != model.Email)
            {
                var existingUser = await _userManager.FindByEmailAsync(model.Email);
                if (existingUser != null)
                {
                    ModelState.AddModelError("Email", "该邮箱已被使用");
                    return View(model);
                }
                user.Email = model.Email;
            }

            var result = await _userManager.UpdateAsync(user);
            if (result.Succeeded)
            {
                await _signInManager.RefreshSignInAsync(user);
                _logger.LogInformation("用户 {UserName} 更新个人资料成功", user.UserName);
                TempData["SuccessMessage"] = "个人资料更新成功";
                return RedirectToAction(nameof(Profile));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return View(model);
        }

        private IActionResult RedirectToLocal(string? returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public IActionResult AccessDenied(string? returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }
    }
} 